<?php
namespace app\api\controller;

use app\api\model\Cart;
use app\api\model\Configs;
use app\api\model\Goods;
use app\api\model\UserAddress;
use think\helper\Str;
use think\Request;

//use app\api\model\Product;

class Orders extends Base
{
    // 不需要验证
    protected $excludeValidateCheck = [

    ];

    // 定义自动实例化模型
    protected $ModelPath = 'Orders';

    public function information(){
        //整理数据
        $data = [
//            search: {enable: false, placeholder: '', button: ''},
//					types: {enable: false, lists: [{alias: '', name: ''}]},
//					popups: {services: {title: '', lists: [], tel: ''}}

            'search'=>[
                'enable'=>true,
                'placeholder'=>'',
                'button'=>'搜索',
            ],
            'types'=>[
                'enable'=>true,
                'lists'=>[
                    [
                        'alias'=>'all',
                        'name'=>'全部',
                    ],
                    [
                        'alias'=>'paying',
                        'name'=>'待付款',
                    ],
                    [
                        'alias'=>'pending',
                        'name'=>'待发货',
                    ],
                    [
                        'alias'=>'delivery',
                        'name'=>'待收货',
                    ],
                    [
                        'alias'=>'received',
                        'name'=>'售后服务',
                    ],
                ]
            ],
            'popups'=>[
                'enable'=>true,
                'services'=>[
                        'title'=>'',
                        'params'=>[],
                        'tel'=>'',
                ]
            ],
        ];

        return showSuccess($data);
    }
    public function detailInformation(){
        $params = request()->param();
        $ordersId = $params['id'];
        $ordersInfos = $this->M
            ->with(['ordersGoods'])
            ->append(['status_format', 'count', 'params'])
            ->find($ordersId);
        $addressInfos = [
            'contact_name'=>$ordersInfos['consignee'],
            'contact_mobile'=>$ordersInfos['phone'],
            'full_address'=>$ordersInfos['province_name'] . $ordersInfos['city_name'] . $ordersInfos['area_name'] . $ordersInfos['address'],
//            'contact_name'=>$ordersInfos['contact_name'],
//            'contact_name'=>$ordersInfos['contact_name'],
        ];
        $goodsInfos = [
            'goods_cover'=>$ordersInfos['goods_cover'],
            'goods_title'=>$ordersInfos['goods_title'],
            'unit_good_amount'=>$ordersInfos['amount'],
            'total_goods_count'=>$ordersInfos['count'],
        ];

        $buttons_array = [];
        if($ordersInfos['status'] == 'paying')
        {
//            $order_action = $ordersInfos['status'] == 'paying' ? 'pay' : '';
            $buttons_array[] = [
                'active'=>'bg',
                'name'=>'立即付款',
                'params'=>['union_order_sn'=>$ordersInfos['order_sn']],
                'alias'=>'cashier',
                'action'=>'pay'
            ];
        }
        //整理数据
        $data = [
//            params: {},
//            address: {},
//            express_img: '',
//            good: {},
//            popups: {services: {title: '', lists: [], tel: ''}},
//            status: '',
//            buttons: [],
//            infos: {enable: false, title: '', lists: []},
//            discounts: {enable: false, title: '', lists: []},
//            expresses: {enable: false, title: '', lists: []},
//            amounts: {goods_amount: 0, express_amount: 0, discount_amount: 0, pay_amount: 0},
//            after_sale: {enable: false, title: '', params: {}}

            'params'=>['union_order_sn'=>$ordersInfos['order_sn']],
            'address'=>$addressInfos,
            'express_img'=>'',
            'good'=>$goodsInfos,
            'popups'=>[
                'services'=>[
                    'title'=>'',
                    'params'=>[],
                    'tel'=>'',
                ]
            ],
            'status'=>'',
            'buttons'=>$buttons_array,
            'infos'=>[
                'enable'=>true,
                'title'=>'基本信息',
                'lists'=>[
                    [
                        'name'=>'订单号',
                        'text'=>$ordersInfos['order_sn']
                    ],
                    [
                        'name'=>'下单时间',
                        'text'=>$ordersInfos['create_time']
                    ],
                    [
                        'name'=>'支付时间',
                        'text'=>$ordersInfos['pay_time']
                    ],
                    [
                        'name'=>'发货时间',
                        'text'=>$ordersInfos['dispatch_date']
                    ],
//                    [
//                        'name'=>'收货时间',
//                        'text'=>$ordersInfos['create_time']
//                    ],
                    [
                        'name'=>'发货物流',
                        'text'=>''
                    ],
//                    [
//                        'name'=>'',
//                        'text'=>''
//                    ],
                ]
            ],
            'discounts'=>[
                'enable'=>false,
                'title'=>'',
                'lists'=>[
                    [

                    ],
                ]
            ],
            'expresses'=>[
                'enable'=>false,
                'title'=>'',
                'lists'=>[[]]
            ],
            'amounts'=>[
                'goods_amount'=>$ordersInfos['total_original_amount'],
                'express_amount'=>0,
                'pay_amount'=>$ordersInfos['total_amount'],
                'discount_amount'=>$ordersInfos['discount_amount']
            ],
            'after_sale'=>[
                'enable'=>false,
                'title'=>'',
                'params'=>[],
            ],
        ];

        return showSuccess($data);
    }

    public function create(Request $request)
    {
        $isOpen = Configs::where('alias', 'IS_OPEN_WITHDRAWAL')->value('content');
        if($isOpen == 0){
            return showError('静态释放准备中');
        }

        $userId = $user_id = request()->UserModel->id;
        $user_level_id = request()->UserModel->virtual_level_id;
        $goods_amount_key = 'sale_amount';
//        if($user_level_id > 0)
//        {
//            $goods_amount_key = $goods_amount_key . $user_level_id;
//        }
        if($user_level_id > 0)
        {
            $goods_amount_key = $user_level_id > 5 ? 'sale_amount5' : 'sale_amount' . $user_level_id;
        }

        $orderData = request()->param();
        if(empty($orderData['address_id'])){
            return showError('请先选择收货地址');
        }
        $cartId = $orderData['ids'];
        $cart = Cart::find($cartId);

        $goods_id = $cart['goods_id'];
        $goods_num = $cart['goods_num'];

        $goods = Goods::find($goods_id);
        if($goods['stock'] == 0)
        {
            return showError('已抢完，预售中');
        }
        //计算金额
        //商品原价
        $goods_original_amount = $goods['sale_amount'];
        //商品折扣后价格
        $goods_amount = $goods[$goods_amount_key];
        //商品总原价
        $total_original_amount = bcmul($goods_original_amount, $goods_num);
        //商品总价
        $total_amount = bcmul($goods_amount, $goods_num);
        //总折扣金额
        $discount_amount = bcsub($total_original_amount, $total_amount);


//        $skuId = $cart['sku_id'];
//        $productSku = ProductSku::find($skuId);
//
//        //先判断是否还有库存
//        if($productSku['stock'] == 0 || $productSku['stock'] < 0){
//            return showError('今日已售罄');
//        }elseif ($productSku['stock'] < $num){
//            return showError('库存不足');
//        }
        //有库存再删
        Cart::destroy($cartId);

        //运费
        $expressPrice = 0;//12;
//        //total_fee实际支付金额 goods_original_amount商品总原价 total_amount总金额 goods_amount商品金额
//        $orderData['goods_amount'] = $orderData['goods_original_amount'] = $productSku['price'] * $num;
//        $orderData['total_amount'] = $orderData['total_fee'] = $orderData['goods_amount'] + $expressPrice;


//        dd($orderData);
        $insertData = [
            // 用户id
            'user_id'                  => $userId,
            // 商品ID
            'goods_id'                  => $goods_id,
            // 商品数量
            'goods_num'                  => $goods_num,
            //  状态
            'status'                => 'paying',
            // 支付类型
            'pay_type'              => null,
            // 订单号
            'order_sn'              => 'SHOP-' . date('YmdHis').strtoupper(Str::random()),// . (microtime(true) * 10),
            // 平台
            'platform'              => request()->header('platform'),//request()->header('platform', 'H5'),

            // 商品金额
            'goods_amount'          => $goods_amount,
            // 运费
            'dispatch_amount'       => $expressPrice,
            // 总金额
            'total_amount'          => $total_amount,
            // 商品总原价
            'goods_original_amount' => $goods_original_amount,

            'total_original_amount' => $total_original_amount,

            'discount_amount' => $discount_amount,
            // 优惠券金额
            'coupon_fee'            => 0,
            // 使用的 用户的优惠券 id
            'coupons_id'            => 0,
//            //  取货方式
//            'dispatch_type'         => 'express',
//            //  取货电话
//            'dispatch_phone'        => $orderData['address']['phone'],
            // 实际已支付金额
//            'pay_fee'               => null,
//            // 积分花费
//            'score_fee'             => null,
            // 商家备忘录
//            'memo'                  => null,

            // 额外信息
//            'ext'                   => json_encode([
//                'buy_type'     => $orderData->goods[0]['buy_type'] ?? 'alone',
//                //                'groupon_id'   => $orderData->groupon_id,
//                'expired_time' => time() + floatval(config('wxapp_config.end_time_min')) * 60,
//            ]),


            //  活动类型
//            'activity_type'         => $orderData->activity_type,

            //  备注
//            'remark'                => request()->post('remark'),
//            // 交易id
//            'transaction_id'        => null,
//            // 支付参数json,用于前端调起支付
//            'payment_json'          => null,
//            // 支付时间
//            'pay_time'              => null,
//            // 支付时间
//            'done_time'             => null,
//            'merchant_id'=>$goods['merchant_id'],
            // 分享人
//            'share_id'              => $orderData->share_id,
            // 分享商品
//            'share_goods_id'        => $orderData->share_goods_id,
            // 支付类型
//            'merchants_type'        => 'online',

        ];
        //获取用户收货地址信息
        $user_address_id = (int)$request->param('address_id', 0);
        //查询地址信息
        if ($address_info = ($user_address_id > 0 ? UserAddress::where('id', $user_address_id)->field(['phone', 'consignee', 'province_name', 'city_name', 'area_name', 'address', 'province_id', 'city_id', 'area_id'])->findOrEmpty()->toArray() : [])) {
            //追加订单信息
            $insertData = array_merge($insertData, $address_info);
        }

        $order = $this->M->create($insertData);
        $data['union_order_sn'] = $order['order_sn'];

        return showSuccess($data);
    }

    public function lists(){
        $params = request()->param();
        $currentPage = request()->param('page', 1);
        $start = ($currentPage - 1) * $this->pageSize;//1 0, 2 10, 3 20
        $type = request()->param('type', 'all');

        $userId = request()->UserModel->id;
        $map = [];

//        $model = $this->M->with(['ordersGoods']);
        if($type != 'all')
        {
            switch ($type){
                case 'paying':
                    $map[] = ['status', '=', $type];
                    break;
                case 'pending':
                    $map[] = ['status', '=', 'payed'];
                    $map[] = ['ship_status', '=', 'pending'];
                    break;
                case 'delivery':
                    $map[] = ['status', '=', 'payed'];
                    $map[] = ['ship_status', '=', 'delivery'];
                    break;
                case 'received':
                    $map[] = ['status', '=', 'payed'];
                    $map[] = ['ship_status', '=', 'received'];
                    break;
            }
        }
        $list = $this->M->with(['ordersGoods'])
            ->where($map)
            ->where('user_id', $userId)
            ->append(['status_format', 'count', 'params'])
            ->order('id DESC')
            ->limit($start, $this->pageSize)
            ->select();
//            ->paginate($this->pageSize)
//            ->toArray();
        $data = [];
//        $data['total_page'] = (int)ceil($list['total']/$this->pageSize);;
        $data['page_size'] = $this->pageSize;
        $data['page'] = $currentPage;//$list['current_page'];
        $data['lists'] = $list;// $list['data'];

        return showSuccess($data);
    }
}